import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BrachistochroneAnimation extends JPanel implements ActionListener {

    private final int a = 100; // 摆线参数
    private final int totalSteps = 200; // 动画步数
    private int step = 0;

    private final Timer timer = new Timer(30, this); // 每30ms刷新一次

    public static void main(String[] args) {
        JFrame frame = new JFrame("最速降曲线动画演示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.add(new BrachistochroneAnimation());
        frame.setVisible(true);
    }

    public BrachistochroneAnimation() {
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        // 平移画布，使图像更居中
        g2.translate(100, 100);
        g2.setStroke(new BasicStroke(2));

        // ---------- 1. 绘制坐标路径 ----------
        // 直线轨迹（灰色）
        g2.setColor(Color.LIGHT_GRAY);
        g2.drawLine(0, 0, 400, 300);

        // 摆线路径（蓝色）
        g2.setColor(Color.BLUE);
        int prevX = 0;
        int prevY = 0;
        for (int i = 1; i <= 300; i++) {
            double t = (Math.PI * i) / 300;
            int x = (int) (a * (t - Math.sin(t)));
            int y = (int) (a * (1 - Math.cos(t)));
            if (i > 1) {
                g2.drawLine(prevX, prevY, x, y);
            }
            prevX = x;
            prevY = y;
        }

        // ---------- 2. 滑动小球 ----------
        double t = (Math.PI * step) / totalSteps;

        // 摆线上小球位置（红色）
        int x1 = (int) (a * (t - Math.sin(t)));
        int y1 = (int) (a * (1 - Math.cos(t)));
        g2.setColor(Color.RED);
        g2.fillOval(x1 - 6, y1 - 6, 12, 12);

        // 直线小球位置（绿色）
        int x2 = (int) (400.0 * step / totalSteps);
        int y2 = (int) (300.0 * step / totalSteps);
        g2.setColor(Color.GREEN.darker());
        g2.fillOval(x2 - 6, y2 - 6, 12, 12);

        // ---------- 3. 起点和终点 ----------
        g2.setColor(Color.BLACK);
        g2.drawString("起点 A", -15, -10);
        g2.drawString("终点 B", 410, 310);

        g2.fillOval(-4, -4, 8, 8);
        g2.fillOval(400 - 4, 300 - 4, 8, 8);

        // ---------- 4. 时间对比显示 ----------
        g2.drawString("红色 = 最速降曲线", 10, 350);
        g2.drawString("绿色 = 直线路径", 10, 370);

        if (step >= totalSteps) {
            timer.stop();
            g2.setFont(new Font("Serif", Font.BOLD, 20));
            g2.setColor(Color.MAGENTA.darker());
            g2.drawString("→ 红色更快到达终点！", 150, 400);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (step <= totalSteps) {
            step++;
            repaint();
        }
    }
}
